% MATRIX INVERSION
% ==============================================================
% This algorithm generates inverse matrix to a square matrix A.
% The algorithm implements the elimination technique. 
function iA = mat_inverse( A )
	mat_size=rows(A);
	if( mat_size != columns(A) )
		disp("Error: matrix is not square");
		iA=-1;
		return;
	endif

	X=zeros(mat_size,mat_size);
	for i=1:mat_size
		X(i,i)=1;
	endfor

	d=1;
	for k=1:mat_size
		d=A(k,k)*d;
		t=A(k,k);
		for j=1:mat_size
			A(k,j)=A(k,j)/t;
			X(k,j)=X(k,j)/t;
		endfor %j
		for i=1:mat_size
			t=A(i,k);
			if( i!=k )
				for j=1:mat_size
					A(i,j)=A(i,j)-t*A(k,j);
					X(i,j)=X(i,j)-t*X(k,j);
				endfor %j
			endif
		endfor % i
	endfor % k
	iA=X;
endfunction


